package com.bdjk.bdmw.InfoGath.communication.server.tcp.netty;

import com.bdjk.bdmw.InfoGath.common.constants.ChannelMap;
import com.bdjk.bdmw.InfoGath.communication.dataProcess.DataProcess;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

public class TCPServerHandlerTest
  extends ChannelInboundHandlerAdapter
{
  private static Map<String, Channel> map = ChannelMap.channelMap;
  private static List<Channel> channel = new ArrayList();
  private static final Logger logger = Logger.getLogger(TCPServerHandlerTest.class);
  
  public void channelRegistered(ChannelHandlerContext ctx)
    throws Exception
  {
    super.channelRegistered(ctx);
    channel.add(ctx.channel());
  }
  
  public void channelRead(ChannelHandlerContext ctx, Object msg)
    throws Exception
  {
    ByteBuf result = (ByteBuf)msg;
    byte[] result1 = new byte[result.readableBytes()];
    
    result.readBytes(result1);
    String resultStr = new String(result1);
    logger.info("Server--------" + resultStr + "---------");
    

    result.release();
    DataProcess dataProcess = new DataProcess();
    dataProcess.messageHandle(resultStr);
    map.put(dataProcess.terIdent, ctx.channel());
    if ((dataProcess.protocol != null) && (dataProcess.isResponse))
    {
     
      

      String terIdent = dataProcess.terIdent;
      String response = dataProcess.responseMsg;
      logger.info("Response--------" + response + "---------");

      ByteBuf encoded = ctx.alloc().buffer(4 * response.length());
      encoded.writeBytes(response.getBytes());
      ctx.write(encoded);
      ctx.flush();
    }
    else
    {
      ctx.writeAndFlush("");
    }
    
    SendClientCommand sendCommand=new SendClientCommand();
    
    //Thread.sleep(50000);
   // logger.info("Server--------" + dataProcess.protocol.smsShutdown + "---------");
    //sendCommand.send(dataProcess.protocol.terIdent, dataProcess.protocol.smsShutdown);
    //Thread.sleep(50000);
    
    //sendCommand.send(dataProcess.protocol.terIdent, dataProcess.protocol.off);
  }
  
  public void channelReadComplete(ChannelHandlerContext ctx)
    throws Exception
  {
    super.channelReadComplete(ctx);
    ctx.flush();
  }
}
